package com.dreamer.view.lottery;


import com.dreamer.domain.lottery.Activity;
import com.dreamer.service.lottery.ActivityHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ps.mx.otter.utils.message.Message;
import java.util.Optional;

@RestController
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private ActivityHandler activityHandler;

    @RequestMapping(value = "/edit.json", method = RequestMethod.POST)
    public Message edit(@ModelAttribute("parameter") Activity activity) {
        try {
            activityHandler.saveOrupdate(activity);

            return Message.createSuccessMessage();
        } catch (Exception exp) {
            exp.printStackTrace();
            return Message.createFailedMessage();
        }
    }

    @RequestMapping(value = "/remove.json", method = RequestMethod.DELETE)
    public Message remove(@ModelAttribute("parameter") Activity activity) {
        try {
            activityHandler.removeActivity(activity);
            return Message.createSuccessMessage();
        } catch (Exception exp) {
            exp.printStackTrace();
            return Message.createFailedMessage();
        }
    }

    @ModelAttribute("parameter")
    public Activity preprocess(@RequestParam("id") Optional<Integer> id) {
        Activity activity = new Activity();
        if (id.isPresent()) {
            activity = activityHandler.findById(id.get());
        }
        return activity;
    }

}
